package com.wing.product.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.*;

import com.wing.product.model.request.ProOutsourcingOrderAddOrUpdateForm;
import com.wing.product.model.response.ProOutsourcingOrderSearchVO;
import com.wing.product.service.ProOutsourcingOrderProductDetailService;
import com.wing.product.service.ProOutsourcingOrderProductService;
import com.wing.product.service.ProOutsourcingOrderService;
import com.wing.res.model.entity.ReceiptRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 委外订单管理
 * @author hz
 */
@Validated
@Api(value = "Admin-委外订单管理", tags = "#/product/outsourcing/outSour")
@RestController("proOutsourcingOrderController")
@RequestMapping("product/admin/outsourcingOrder")
public class ProOutsourcingOrderController {

    @Autowired
    private ProOutsourcingOrderService proOutsourcingOrderService;

    @Autowired
    private ProOutsourcingOrderProductDetailService proOutsourcingOrderProductDetailService;

    @Autowired
    private ProOutsourcingOrderProductService proOutsourcingOrderProductService;



    @ApiOperation(value = "查询所有产委外订单管理", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProOutsourcingOrder> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String supplierId
            ,String code
            ,String departmentId
            ,String status
            ,String type
            ,String startTime
            ,String endTime
    ){


        Page<ProOutsourcingOrder> pg = new Page<>(page, limit);

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", StrUtil.toUnderlineCase(order));
        paramMap.put("supplierId", supplierId);
        paramMap.put("departmentId", departmentId);
        paramMap.put("code", code);
        paramMap.put("type", type);
        paramMap.put("status", status);
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        IPage<ProOutsourcingOrder> list = proOutsourcingOrderService.pageList4app(pg, paramMap);
        list.getRecords().forEach(info->{
            //查询 总sku数  总产品数 总金额
            QueryWrapper<ProOutsourcingOrderProduct> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", info.getId());
            queryWrapper.eq("is_deleted", 0);
            List<ProOutsourcingOrderProduct> proOutsourcingOrderProducts = proOutsourcingOrderProductService.list(queryWrapper);
            int skuCount = 0;
            int productCount = 0;
            BigDecimal skuPrice = BigDecimal.ZERO;
            if (CollectionUtil.isNotEmpty(proOutsourcingOrderProducts)) {
                skuCount = proOutsourcingOrderProducts.size();
                for (ProOutsourcingOrderProduct proOutsourcingOrderProduct : proOutsourcingOrderProducts) {
                    if (proOutsourcingOrderProduct.getQuantity()!=null){
                        productCount += proOutsourcingOrderProduct.getQuantity();
                    }
                    if (ObjectUtil.isNotEmpty(proOutsourcingOrderProduct.getQuantity())&& ObjectUtil.isNotEmpty(proOutsourcingOrderProduct.getCurrentCostPrice())){
                        new BigDecimal(proOutsourcingOrderProduct.getQuantity());
                        BigDecimal count = proOutsourcingOrderProduct.getCurrentCostPrice().multiply(new BigDecimal(proOutsourcingOrderProduct.getQuantity()));
                        skuPrice = skuPrice.add(count);
                    }
                }
            }
            info.setSkuCount(skuCount);
            info.setProductCount(productCount);
            info.setTotalPrice(skuPrice);
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 添加委外订单
     * @param proOutsourcingOrderAddOrUpdateForm 添加委外订单入参
     * @return 是否添加成功
     */
    @ApiOperation(value = "添加委外订单", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@RequestBody ProOutsourcingOrderAddOrUpdateForm proOutsourcingOrderAddOrUpdateForm) {
        Boolean isOk = proOutsourcingOrderService.add(proOutsourcingOrderAddOrUpdateForm);
        if (isOk) {
            return JsonResult.success("添加成功！");
        }else{
            return JsonResult.success("添加失败！");
        }
    }


    /**
     * 查询委外订单详情
     * @param orderId 订单id
     * @return 订单详情
     */
    @ApiOperation(value = "查看委外订单详情", notes = "添加")
    @GetMapping("/detail/{orderId}")
    public JsonResult detail(@PathVariable("orderId") Long orderId) {
        ProOutsourcingOrderSearchVO vo = proOutsourcingOrderService.getDetailBy(orderId);
        return JsonResult.success(vo);
    }

    /**
     * 修改委外订单
     * @param proOutsourcingOrderAddOrUpdateForm 添加委外订单入参
     * @return 是否添加成功
     */
    @ApiOperation(value = "修改委外订单", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody ProOutsourcingOrderAddOrUpdateForm proOutsourcingOrderAddOrUpdateForm) {
        Boolean isOk = proOutsourcingOrderService.updateBy(proOutsourcingOrderAddOrUpdateForm);
        if (isOk) {
            return JsonResult.success("修改成功！");
        }else{
            return JsonResult.success("修改失败！");
        }
    }

    /**
     * 审核委外订单
     * @param orderId 订单id
     * @param status 状态
     * @return 是否添加成功
     */
    @ApiOperation(value = "审核委外订单", notes = "审核")
    @PostMapping("/audit/{orderId}/{status}")
    public JsonResult audit(@PathVariable("orderId") Long orderId,@PathVariable("status") String status) {
        Boolean isOk = proOutsourcingOrderService.audit(orderId,status);
        if (isOk) {
            return JsonResult.success("操作成功！");
        }else{
            return JsonResult.success("无权限操作or状态不为待审核！");
        }
    }

    /**
     * 提交委外订单
     * @param orderId 订单id
     * @return 是否添加成功
     */
    @ApiOperation(value = "提交委外订单", notes = "提交")
    @PostMapping("/submit/{orderId}")
    public JsonResult audit(@PathVariable("orderId") Long orderId) {
        Boolean isOk = proOutsourcingOrderService.submit(orderId);
        if (isOk) {
            return JsonResult.success("操作成功！");
        }else{
            return JsonResult.success("操作失败！");
        }
    }
}
